#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QFileInfo>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget),
    m_currentContactId(-1)
{
    ui->setupUi(this);

    // 初始化数据库处理器
    m_dbHandler = new DatabaseHandler(this);

    // 设置数据库路径（与程序同目录下的contacts.accdb）
    QString dbPath = QCoreApplication::applicationDirPath() + "/contacts.accdb";
    qDebug()<<dbPath;

    // 检查QT构建版本
        qDebug() << "Build ABI:" << QSysInfo::buildAbi();
        qDebug() << "Word size:" << QSysInfo::WordSize << "bits";


        qDebug() << "Available database drivers:";
            QStringList drivers = QSqlDatabase::drivers();
            foreach (QString driver, drivers) {
                qDebug() << driver;
            }

    // 初始化数据库连接
    if (!m_dbHandler->initDatabase(dbPath)) {
        QMessageBox::critical(this, "Database Error",
                            "Failed to initialize database:\n" + m_dbHandler->lastError());
        qApp->quit(); // 退出应用
    }

    // 设置表格
    setupTable();

    // 刷新联系人列表
    refreshContactList();

    // 连接信号槽
    connect(ui->addButton, &QPushButton::clicked, this, &Widget::onAddContact);
    connect(ui->editButton, &QPushButton::clicked, this, &Widget::onEditContact);
    connect(ui->deleteButton, &QPushButton::clicked, this, &Widget::onDeleteContact);
    connect(ui->contactTable, &QTableWidget::clicked, this, &Widget::onContactSelected);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::setupTable()
{
    // 设置表格列数和标题
    ui->contactTable->setColumnCount(4);
    QStringList headers;
    headers << "ID" << "Name" << "Phone" << "Email";
    ui->contactTable->setHorizontalHeaderLabels(headers);

    // 设置表格属性
    ui->contactTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->contactTable->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->contactTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->contactTable->horizontalHeader()->setStretchLastSection(true);
    ui->contactTable->setColumnHidden(0, true); // 隐藏ID列
}

void Widget::refreshContactList()
{
    // 清空表格
    ui->contactTable->setRowCount(0);

    // 从数据库获取所有联系人
    auto contacts = m_dbHandler->getAllContacts();

    // 填充表格
    for (const auto &contact : contacts) {
        int row = ui->contactTable->rowCount();
        ui->contactTable->insertRow(row);

        ui->contactTable->setItem(row, 0, new QTableWidgetItem(contact[0].toString()));
        ui->contactTable->setItem(row, 1, new QTableWidgetItem(contact[1].toString()));
        ui->contactTable->setItem(row, 2, new QTableWidgetItem(contact[2].toString()));
        ui->contactTable->setItem(row, 3, new QTableWidgetItem(contact[3].toString()));
    }
}

void Widget::onAddContact()
{
    // 获取输入内容
    QString name = ui->nameEdit->text().trimmed();
    QString phone = ui->phoneEdit->text().trimmed();
    QString email = ui->emailEdit->text().trimmed();
    QString address = ui->addressEdit->toPlainText().trimmed();

    // 验证输入
    if (name.isEmpty()) {
        QMessageBox::warning(this, "Warning", "Name cannot be empty!");
        return;
    }

    // 添加到数据库
    if (m_dbHandler->addContact(name, phone, email, address)) {
        QMessageBox::information(this, "Success", "Contact added successfully!");
        refreshContactList();
        clearInputFields();
    } else {
        QMessageBox::critical(this, "Error", "Failed to add contact:\n" + m_dbHandler->lastError());
    }
}

void Widget::onEditContact()
{
    if (m_currentContactId == -1) {
        QMessageBox::warning(this, "Warning", "Please select a contact to edit!");
        return;
    }

    // 获取输入内容
    QString name = ui->nameEdit->text().trimmed();
    QString phone = ui->phoneEdit->text().trimmed();
    QString email = ui->emailEdit->text().trimmed();
    QString address = ui->addressEdit->toPlainText().trimmed();

    // 验证输入
    if (name.isEmpty()) {
        QMessageBox::warning(this, "Warning", "Name cannot be empty!");
        return;
    }

    // 更新数据库
    if (m_dbHandler->updateContact(m_currentContactId, name, phone, email, address)) {
        QMessageBox::information(this, "Success", "Contact updated successfully!");
        refreshContactList();
    } else {
        QMessageBox::critical(this, "Error", "Failed to update contact:\n" + m_dbHandler->lastError());
    }
}

void Widget::onDeleteContact()
{
    if (m_currentContactId == -1) {
        QMessageBox::warning(this, "Warning", "Please select a contact to delete!");
        return;
    }

    // 确认删除
    if (QMessageBox::question(this, "Confirm",
                             "Are you sure you want to delete this contact?",
                             QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) {
        return;
    }

    // 从数据库删除
    if (m_dbHandler->deleteContact(m_currentContactId)) {
        QMessageBox::information(this, "Success", "Contact deleted successfully!");
        m_currentContactId = -1;
        refreshContactList();
        clearInputFields();
    } else {
        QMessageBox::critical(this, "Error", "Failed to delete contact:\n" + m_dbHandler->lastError());
    }
}

void Widget::onContactSelected(const QModelIndex &index)
{
    // 获取选中行的ID
    int row = index.row();
    m_currentContactId = ui->contactTable->item(row, 0)->text().toInt();

    // 从数据库获取联系人详情
    auto contact = m_dbHandler->getContactById(m_currentContactId);
    if (contact.isEmpty()) {
        QMessageBox::critical(this, "Error", "Failed to load contact details!");
        return;
    }

    // 填充到输入框
    ui->nameEdit->setText(contact[1].toString());
    ui->phoneEdit->setText(contact[2].toString());
    ui->emailEdit->setText(contact[3].toString());
    ui->addressEdit->setPlainText(contact[4].toString());
}

void Widget::clearInputFields()
{
    ui->nameEdit->clear();
    ui->phoneEdit->clear();
    ui->emailEdit->clear();
    ui->addressEdit->clear();
    m_currentContactId = -1;
}
